<template>
  <div>
    <!-- 页面标题 -->

    <!-- 搜索 -->
    <v-row class="mb-6">

      <v-col cols="12">
        <v-text-field v-model="searchText" prepend-inner-icon="mdi-magnify" label="搜索教师姓名、用户名或电话" variant="filled"
          density="comfortable" clearable></v-text-field>
      </v-col>
    </v-row>
    <v-btn color="primary" prepend-icon="mdi-plus" @click="openTeacherDialog()">
      添加教师
    </v-btn>
    <!-- 教师列表 -->
    <v-card>
      <v-card-text>
        <!-- 移动端完整视图 -->
        <div v-if="mobile" class="mobile-teacher-list">
          <v-card
            v-for="teacher in paginatedMobileTeachers"
            :key="teacher.id"
            class="mb-3"
            variant="outlined"
          >
            <v-card-text class="pa-2">
              <!-- 头部信息：姓名、用户名、电话 -->
              <div class="d-flex align-center mb-2">
                <v-avatar color="primary" size="32" class="me-2">
                  <span class="text-white text-caption">{{ teacher.name.charAt(0) }}</span>
                </v-avatar>
                <div class="flex-grow-1">
                  <div class="d-flex align-center justify-space-between">
                    <div>
                      <div class="font-weight-medium text-body-2">{{ teacher.name }}</div>
                      <div class="text-caption text-medium-emphasis">{{ teacher.username }}</div>
                    </div>
                    <div v-if="teacher.phone" class="d-flex align-center">
                      <v-icon size="12" class="me-1" color="medium-emphasis">mdi-phone</v-icon>
                      <a :href="`tel:${teacher.phone}`" class="text-caption text-decoration-none text-medium-emphasis">
                        {{ teacher.phone }}
                      </a>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 负责班级：紧凑显示 -->
              <div class="mb-2">
                <div class="d-flex align-center gap-1">
                  <v-icon size="14" color="medium-emphasis">mdi-school</v-icon>
                  <span class="text-caption text-medium-emphasis">班级:</span>
                  <div v-if="teacher.classes" class="d-flex flex-wrap gap-1">
                    <v-chip v-for="cls in teacher.classes.split(', ')" :key="cls" size="x-small" variant="outlined" color="blue">
                      {{ cls }}
                    </v-chip>
                  </div>
                  <span v-else class="text-caption text-medium-emphasis">未分配</span>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="d-flex justify-end gap-1">
                <v-btn
                  size="small"
                  variant="outlined"
                  color="primary"
                  icon="mdi-pencil"
                  @click="openTeacherDialog(teacher)"
                ></v-btn>
                <v-btn
                  size="small"
                  variant="outlined"
                  color="error"
                  icon="mdi-delete"
                  @click="deleteTeacher(teacher)"
                ></v-btn>
              </div>
            </v-card-text>
          </v-card>
          
          <!-- 移动端分页 -->
          <div class="d-flex justify-center mt-4">
            <v-pagination
              v-model="mobilePage"
              :length="mobilePageCount"
              :total-visible="5"
              size="small"
            ></v-pagination>
          </div>
        </div>

        <!-- 桌面端数据表格 -->
        <v-data-table v-else :headers="headers" :items="filteredTeachers" :loading="loading" class="elevation-1"
          :items-per-page="10">
          <template v-slot:item.name="{ item }">
            <div class="d-flex align-center">
              <v-avatar color="primary" size="40" class="me-3">
                <span class="text-white">{{ item.name.charAt(0) }}</span>
              </v-avatar>
              <div>
                <div class="font-weight-medium">{{ item.name }}</div>
                <div class="text-caption text-medium-emphasis">{{ item.username }}</div>
              </div>
            </div>
          </template>

          <template v-slot:item.contact="{ item }">
            <div>
              <div v-if="item.phone" class="d-flex align-center mb-1">
                <v-icon size="16" class="me-2">mdi-phone</v-icon>
                <a :href="`tel:${item.phone}`" class="text-decoration-none">
                  {{ item.phone }}
                </a>
              </div>

            </div>
          </template>

          <template v-slot:item.classes="{ item }">
            <div v-if="item.classes">
              <v-chip v-for="cls in item.classes.split(', ')" :key="cls" size="small" class="ma-1" color="blue">
                {{ cls }}
              </v-chip>
            </div>
            <span v-else class="text-medium-emphasis">未分配班级</span>
          </template>

          <template v-slot:item.created_at="{ item }">
            {{ formatDate(item.created_at) }}
          </template>

          <template v-slot:item.actions="{ item }">
            <v-btn icon size="small" variant="text" @click="openTeacherDialog(item)">
              <v-icon>mdi-pencil</v-icon>
            </v-btn>



            <v-btn icon size="small" variant="text" color="error" @click="deleteTeacher(item)">
              <v-icon>mdi-delete</v-icon>
            </v-btn>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 教师编辑对话框 -->
    <v-dialog v-model="teacherDialog" max-width="600">
      <v-card>
        <v-card-title>
          {{ editingTeacher?.id ? '编辑教师' : '添加教师' }}
        </v-card-title>

        <v-card-text>
          <v-form ref="teacherFormRef" @submit.prevent="saveTeacher">
            <v-row>
              <v-col cols="12" sm="6">
                <v-text-field v-model="teacherForm.username" label="用户名" variant="filled" density="comfortable"
                  :rules="usernameRules" :disabled="!!editingTeacher?.id" required></v-text-field>
              </v-col>
              <v-col cols="12" sm="6" v-if="!editingTeacher?.id">
                <v-text-field v-model="teacherForm.password" label="密码" type="password" variant="filled"
                  density="comfortable" :rules="passwordRules" required></v-text-field>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field v-model="teacherForm.name" label="姓名" variant="filled" density="comfortable"
                  :rules="nameRules" required></v-text-field>
              </v-col>
              <v-col cols="12" sm="6">
                <v-text-field v-model="teacherForm.phone" label="手机号" variant="filled" density="comfortable"
                  :rules="phoneRules"></v-text-field>
              </v-col>

            </v-row>
          </v-form>
        </v-card-text>

        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="teacherDialog = false">取消</v-btn>
          <v-btn color="primary" @click="saveTeacher" :loading="saving">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>




  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDisplay } from 'vuetify'
import api from '@/utils/api'

const { mobile } = useDisplay()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const teachers = ref([])
const searchText = ref('')
const teacherDialog = ref(false)
const editingTeacher = ref(null)
const mobilePage = ref(1)
const mobileItemsPerPage = ref(10)

const teacherForm = ref({
  username: '',
  password: '',
  name: '',
  phone: ''
})

const teacherFormRef = ref(null)

// 表格标题
const headers = [
  { title: '教师信息', key: 'name', sortable: true },
  { title: '联系方式', key: 'contact', sortable: false },
  { title: '负责班级', key: 'classes', sortable: false },
  { title: '操作', key: 'actions', sortable: false }
]

// 计算属性
const filteredTeachers = computed(() => {
  if (!searchText.value) return teachers.value

  const search = searchText.value.toLowerCase()
  return teachers.value.filter(teacher =>
    teacher.name.toLowerCase().includes(search) ||
    teacher.username.toLowerCase().includes(search) ||
    teacher.phone?.toLowerCase().includes(search)
  )
})

const mobilePageCount = computed(() => {
  return Math.ceil(filteredTeachers.value.length / mobileItemsPerPage.value)
})

const paginatedMobileTeachers = computed(() => {
  const start = (mobilePage.value - 1) * mobileItemsPerPage.value
  const end = start + mobileItemsPerPage.value
  return filteredTeachers.value.slice(start, end)
})

// 验证规则
const usernameRules = [
  v => !!v || '用户名不能为空',
  v => v.length >= 3 || '用户名至少3位',
  v => /^[a-zA-Z0-9_]+$/.test(v) || '用户名只能包含字母、数字和下划线'
]

const passwordRules = [
  v => !!v || '密码不能为空',
  v => v.length >= 6 || '密码至少6位'
]

const nameRules = [
  v => !!v || '姓名不能为空',
  v => v.length >= 2 || '姓名至少2个字符'
]

const phoneRules = [
  v => !v || /^1[3-9]\d{9}$/.test(v) || '请输入正确的手机号'
]



// 方法
const loadTeachers = async () => {
  loading.value = true
  try {
    const response = await api.get('/users/teachers')
    teachers.value = response.data.data
  } catch (error) {
    console.error('加载教师列表失败:', error)
    window.showNotification?.('加载教师列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const openTeacherDialog = (teacher = null) => {
  editingTeacher.value = teacher
  if (teacher) {
    Object.assign(teacherForm.value, {
      username: teacher.username || '',
      name: teacher.name || '',
      phone: teacher.phone || ''
    })
  } else {
    Object.assign(teacherForm.value, {
      username: '',
      password: '',
      name: '',
      phone: ''
    })
  }
  teacherDialog.value = true
}

const saveTeacher = async () => {
  const { valid } = await teacherFormRef.value.validate()
  if (!valid) return

  saving.value = true
  try {
    const payload = { ...teacherForm.value, role: 'teacher' }

    if (editingTeacher.value?.id) {
      // 更新教师 - 移除密码和用户名字段
      const { password, username, ...updateData } = payload
      await api.put(`/users/${editingTeacher.value.id}`, updateData)
      window.showNotification?.('教师信息更新成功', 'success')
    } else {
      // 创建教师
      await api.post('/users', payload)
      window.showNotification?.('教师添加成功', 'success')
    }

    teacherDialog.value = false
    loadTeachers()

  } catch (error) {
    console.error('保存教师失败:', error)
    const message = error.response?.data?.message || '保存教师失败'
    window.showNotification?.(message, 'error')
  } finally {
    saving.value = false
  }
}



const deleteTeacher = async (teacher) => {
  if (!confirm(`确定要删除教师 "${teacher.name}" 吗？\n删除后该教师将无法登录系统。`)) return

  try {
    await api.delete(`/users/${teacher.id}`)
    loadTeachers()
    window.showNotification?.('教师删除成功', 'success')
  } catch (error) {
    console.error('删除教师失败:', error)
    window.showNotification?.('删除教师失败', 'error')
  }
}



const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadTeachers()
})
</script>

<style scoped>
.v-data-table {
  border-radius: 8px;
}

.text-decoration-none {
  text-decoration: none;
  color: inherit;
}

.text-decoration-none:hover {
  text-decoration: underline;
}

.v-btn{
  margin: 10px 0 20px 0;
}
</style>
